<?php
require_once '../entity/Masker.php';
require_once '../entity/Sign.php';
require_once '../services/MailService.php';
require_once 'DaoUtils.php';
class MaskerDao extends DaoUtils {
	public function insertMasker($name, $password, $mail) {
		$name = $this -> escape($name);
		$password = $this -> escape($password);
		$mail = $this -> escape($mail);

		$query = "insert into " . Masker::getTableName() . " (name, password, mail) values ('" . $name . "','" . $password . "', '" . $mail . "')";
		$result = $this -> insert($query);

		$mailService = new MailService();
		$mailService->registerMail($name, $password, $mail);
		
		return $result;
	}

	public function getMasker($id) {
		$query = "select * from " . Masker::getTableName() . " where id = " . $id;
		$record = $this -> selectRecord($query);
		// TODO mappare il masker
		return $record;
	}
	
	public function getMaskerByName($name) {
		$query = "select * from " . Masker::getTableName() . " where name = '" . $name ."'";
		$record = $this -> selectRecord($query);
		return $record;
	}
	
	public function getMaskerInfo($name) {
		$name = $this -> escape($name);
		
		$query = "SELECT id,name, ";
		$query .= "(SELECT COUNT(*) FROM question WHERE id_masker_to = m.id) AS question_count, ";
		$query .= "(SELECT COUNT(*) FROM sign WHERE id_masker = m.id) AS sign_count, ";
		$query .= "(SELECT SUM(colorfeel_b + colorfeel_g + colorfeel_r) FROM " . Sign::getTableName() . " WHERE id_masker = m.id) AS colorfeel_count ";
		$query .= "FROM " . Masker::getTableName() . " as m WHERE m.name = '".$name."'";
		
		$record = $this -> selectRecord($query);
		return $record;
	}

	public function existMasker($name) {
		$name = $this -> escape($name);
		$query = "select count(*) as count from " . Masker::getTableName() . " where name = '" . $name . "'";
		$record = $this -> selectRecord($query);
		return $record["count"] > 0;
	}

	public function checkMaskerAuth($name, $password) {
		$name = $this -> escape($name);
		$password = $this -> escape($password);

		$query = "select * from " . Masker::getTableName() . " where name = '" . $name . "' and password = '" . $password . "'";
		$record = $this -> selectRecord($query);

		if (empty($record)) {
			return null;
		} else {
			return $record;
		}
	}

}
?>